package com.my.reggie.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.my.reggie.mapper.PaymentInfoMapper;
import com.my.reggie.pojo.PaymentInfo;
import com.my.reggie.service.PaymentInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {
    @Override
    public void saveInfo(String decryptData) {
        log.info("记录支付日志");
        JSONObject data = JSON.parseObject(decryptData);
        PaymentInfo paymentInfo = new PaymentInfo();
        //获取订单号
        String orderNumber = (String) data.get("out_trade_no");
        paymentInfo.setOrderNumber(orderNumber);
        //获取支付系统交易编号
        String transactionId = (String) data.get("transaction_id");
        paymentInfo.setTransactionId(transactionId);
        //获取交易类型
        String tradeType = (String) data.get("trade_type");
        paymentInfo.setTradeType(tradeType);
        //获取交易状态
        String tradeState = (String) data.get("trade_state");
        paymentInfo.setTradeState(tradeState);
        //获取交易金额(分)
        JSONObject amount = (JSONObject) data.get("amount");
        int payerTotal = (int) amount.get("payer_total");
        paymentInfo.setPayerTotal(payerTotal);

        //保存支付日志
        this.save(paymentInfo);
    }

    /**
     * 更新支付日志中的订单状态
     * @param number
     */
    @Override
    public void updateStatus(String number,String status) {
        LambdaUpdateWrapper<PaymentInfo> luw = new LambdaUpdateWrapper<>();
        luw.eq(PaymentInfo::getOrderNumber,number);
        luw.set(PaymentInfo::getTradeState,status);

        this.update(luw);
    }
}
